<template>
  <div class="app">
    <view
      class="header"
      :style="{
        paddingTop: safeArea.top + 'px',
        height: view.topBar.bottom + 'px'
      }"
    >
      <div class="position-main" @click="selectAddress()">
        <svg-icon name="map" class="map" size="40rpx"></svg-icon>
        <span class="position-address">
          {{ globalPosition.addressLabel ?? '请选择地址' }}
        </span>
        <uni-icons type="right" size="10"></uni-icons>
      </div>
    </view>

    <scroll-view
      :refresher-enabled="isContainerScrollAllowed"
      @scrolltolower="loadData(true)"
      :scroll-y="isContainerScrollAllowed"
      class="scroll-container"
      :refresher-triggered="isTriggered"
      @refresherrefresh="onRefresherrefresh()"
      :style="{ top: view.topBar.bottom + 'px' }"
      :scroll-top="isContainerScrollAllowed ? 1 : 0"
    >
      <view class="body">
        <!-- 滚动容器 -->
        <view class="search" @click="toSearchPage">
          <span class="mock-input-text">美食一搜就有</span>
          <span class="button">搜索</span>
        </view>

        <view>
          <view class="uni-margin-wrap">
            <swiper
              class="swiper"
              circular
              :indicator-dots="carousel.indicatorDots"
              :autoplay="carousel.autoplay"
              :interval="carousel.interval"
              :duration="carousel.duration"
            >
              <swiper-item>
                <view class="swiper-item uni-bg-red">
                  <img
                    src="https://spark-takeaway.oss-cn-guangzhou.aliyuncs.com/2023-10-28/A.png"
                    class="swiper-item-image"
                  />
                </view>
              </swiper-item>
            </swiper>
          </view>
        </view>
        <NavigatorGrid
          :list="menuList"
          nameFieldName="name"
          :beforeNavigatorToPage="beforeNavigatorToShopCategoryPage"
          iconFieldName="icon"
          urlFieldName="url"
        ></NavigatorGrid>

        <view class="stickyBox">
          <CheckBox
            :options="shopCheckBoxOperation"
            @change="loadData()"
            @call-out="(isCallOut: boolean) => (isContainerScrollAllowed = !isCallOut)"
            class="stickyBox"
            ref="checkBoxRef"
          />
        </view>
        <view class="stores">
          <Shop v-for="(item, index) in nearbyShopPageData" :data="item" :key="index" />
        </view>
        <p class="loading">
          <span v-if="page.total === undefined || page.currentPage < Math.ceil((page.total || 0) / page.pageSize)"
            >正在加载...</span
          >
          <span v-else-if="page.total === 0">附近暂时没有入驻的店铺</span>
          <span v-else>没有更多了</span>
        </p>
      </view>
    </scroll-view>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import NavigatorGrid from '@/components/navigator-grid/index.vue'
import CheckBox from '@/components/check-box/index.vue'
import Shop from '@/components/shop/index.vue'
import SvgIcon from '@/components/SvgIcon/index.vue'
import $store from '@/store'
import $API from '@/api'
import PropertiesCopyUtils from '@/utils/PropertiesCopyUtils'
import type { MixinSurveyItem, Result } from '@/components/check-box/check-box-selector/type'
import { SearchNearbyShopsPage } from '@/types/param/shop'
import { Page } from '@/types/generic/Page'
import { NearbyShop } from '@/types/response/shop'
import shopCheckBoxOperation from '@/common/check-box-operation-store/shopCheckBoxOperation'
import type ShopCategory from '@/types/entity/ShopCategory'
import { $modal } from '@/plugins'
import onReShow from '@/helper/onReShow'

const { safeArea, view, capsule } = $store.app.getSystemParam()
const checkBoxRef = ref()
const globalPosition = $store.user.positionStore.globalLocation
const isContainerScrollAllowed = ref(true)
// 在模板中启用 v-focus
let carousel = ref({
  indicatorDots: true, // 是否开启指示点
  autoplay: true,
  interval: 3000, // 切换间隔时长
  duration: 500 // 切换过程时长
})
let menuList = ref<(ShopCategory & { url?: string })[]>([])
onMounted(async () => {
  const result = await $API.shopCategory.list()
  if (!result.success) {
    $modal.toastErrorMsg('服务错误，请稍后再试')
    return
  }
  menuList.value = result.data.map((item) => {
    return {
      ...item,
      url: `/pages/index/search/index?shopCategoryId=${item.id}`
    }
  })
  console.log('globalPosition.value=', globalPosition)
  globalPosition.requestLocation().then(() => loadData())
})
// 分页参数
const page = ref<Page & { total?: number }>({ ...new Page(), pageSize: 15 })
const nearbyShopPageData = ref<NearbyShop[]>([])
async function loadData(isAppend = false) {
  const results: Result[] = checkBoxRef.value?.getSubmitData()
  const searchNearbyShopsPage = new SearchNearbyShopsPage()
  let conditionObj = results?.reduce(
    (acc, currVal: Result) => {
      acc[currVal.name] = currVal.value
      return acc
    },
    {} as { [key: string]: any }
  )
  isAppend ? page.value.currentPage++ : (page.value.currentPage = 1)
  PropertiesCopyUtils.copy([globalPosition, conditionObj, page.value], searchNearbyShopsPage)
  // 根据是否追加设置加载的页数
  const result = await $API.shop.searchNearbyShops(searchNearbyShopsPage)
  if (result.success) {
    // 前面的不要
    if (isAppend) {
      nearbyShopPageData.value.push(...result.data.list)
    } else {
      // 重置页数
      nearbyShopPageData.value = result.data.list
    }
    page.value.total = parseInt(result.data.total + '')
  }
}

// 下拉刷新状态
const isTriggered = ref(false)
async function onRefresherrefresh() {
  // 开启动画
  isTriggered.value = true
  // 加载下一页追加数据
  page.value.currentPage++
  await Promise.all([loadData()])
  isTriggered.value = false
}

// 去搜索页面
function toSearchPage() {
  uni.navigateTo({
    url: '/pages/index/search/index'
  })
}
// 用户手动选择位置(更新userPosition)
function selectAddress() {
  globalPosition.requestLocationForManual().then(() => loadData())
}
onReShow(() => {
  loadData()
})
// 跳转店铺分类前回调
function beforeNavigatorToShopCategoryPage(item: ShopCategory) {
  // 默认混入SurveyItem的数据
  const mixinSurveyItem: MixinSurveyItem[] = [
    {
      name: 'shopCategory',
      options: [
        {
          label: item.name,
          value: item.id
        }
      ],
      value: item.id
    }
  ]
  $store.shop.conveyerBelt.putIn(item.id, mixinSurveyItem)
}
</script>

<style lang="scss" scoped>
.stickyBox {
  position: sticky;
  top: 0;
  z-index: 100;
}

.app {
  overflow-x: hidden;
  background-color: #f6f6f6;

  .header {
    position: fixed;
    top: 0;
    right: 0;
    left: 0;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding: 0 30rpx;
    box-sizing: border-box;

    /* height: 90rpx; */
    background-color: #ffd350;

    .position-main {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      line-height: 40rpx;
      height: 40rpx;

      .position-address {
        display: inline-block;
        overflow: hidden;
        margin: 0 3rpx 0 5rpx;
        max-width: 300rpx;
        font-size: 30rpx;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #1f2225;
      }
    }
  }

  .scroll-container {
    position: fixed;
    right: 0;
    bottom: 0;
    left: 0;

    // overflow-y: scroll;
    .body {
      position: absolute;
      top: 0;

      .loading {
        height: 70rpx;
        font-size: 28rpx;
        text-align: center;
        color: #5f6368;
        line-height: 70rpx;
      }
    }
  }
}

/** 搜索栏 */
.search {
  z-index: 100;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 10rpx auto;
  padding-right: 3px;
  padding-left: 15px;
  width: 700rpx;
  height: 40px;
  border: 1.5px solid sandybrown;
  border-radius: 20px;
  line-height: 40px;
  box-sizing: border-box;

  .mock-input-text {
    color: #848283;
  }

  .button {
    $height: 32px;

    padding: 0 20px;
    height: $height;
    line-height: $height;
    border-radius: 20px;
    background-color: #ffd350;
  }
}

.uni-margin-wrap {
  margin: 15rpx auto;
  width: 720rpx;
}

.swiper {
  height: 350rpx;
}

.swiper-item {
  display: block;
  height: 100%;
  line-height: 300rpx;
  text-align: center;
}

.swiper-item-image {
  display: block;
  width: 100%;
  height: 100%;
}

.swiper-list {
  margin-top: 40rpx;
  margin-bottom: 0;
}

.uni-common-mt {
  position: relative;
  margin-top: 60rpx;
}

.info {
  position: absolute;
  right: 20rpx;
}

.uni-padding-wrap {
  padding: 0 100rpx;
  width: 550rpx;
}
</style>
